package com.hs.live.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.nacos.shaded.com.google.common.base.Strings;
import com.hs.live.common.entity.response.ResponseCommon;
import com.hs.live.common.enums.ErrorCodeResp;
import com.hs.live.user.dto.CheckSmsDTO;
import com.hs.live.user.dto.MobileLoginUserDTO;
import com.hs.live.user.dto.UserDTO;
import com.hs.live.user.inter.UserRpcService;
import com.hs.live.user.req.MobileLoginUserReq;
import lombok.extern.slf4j.Slf4j;
import org.apache.coyote.Response;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;


/**
 * @Description: User控制层
 * @Author 胡尚
 * @Date: 2024/9/6 10:27
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {


    @DubboReference
    UserRpcService userRpcService;

    @GetMapping("/findById")
    public ResponseCommon<UserDTO> findById(@RequestParam("userId") Long userId, @RequestHeader("userId") Long headUserId) {
        log.info("根据id查询用户的请求参数为{}", userId);
        log.info("从请求头中获取的当前登录的userId为{}", headUserId);
        UserDTO user = userRpcService.getUserById(userId);
        if (user == null){
            return ResponseCommon.error();
        }
        return ResponseCommon.success(user);
    }

    @PostMapping("/sendSms")
    public ResponseCommon sendSms(String phone){
        // 参数校验
        if (Strings.isNullOrEmpty(phone)){
            log.warn("发送短信验证码请求参数不能为null");
            return ResponseCommon.error("请求参数不能为null");
        }

        // 调用远程服务
        if (userRpcService.sendSms(phone)){
            return ResponseCommon.success();
        }else {
            return ResponseCommon.error("短信发送失败");
        }
    }

    /**
     * 使用短信验证码方式登录
     */
    @PostMapping("/checkSms")
    public ResponseCommon<MobileLoginUserDTO> checkSms(@RequestBody MobileLoginUserReq req){
        // 参数校验
        if (Strings.isNullOrEmpty(req.getMobile()) || Strings.isNullOrEmpty(req.getCode())){
            log.info("使用手机号验证码登录接口，请求参数不符合要求{}", JSON.toJSONString(req));
            return ResponseCommon.error("请求参数异常", ErrorCodeResp.REQ_PARAMETER_UNQUALIFIED.getCode());
        }

        // 校验短信验证码是否正常
        CheckSmsDTO checkSmsDTO = userRpcService.checkSms(req);
        if (!checkSmsDTO.getCorrect()){
            log.info("{}手机号短信验证码登录失败，errorCode:{}", req.getMobile(), checkSmsDTO.getErrorCode());
            return ResponseCommon.error("验证码错误或失效", checkSmsDTO.getErrorCode());
        }
        // 判断用户是否注册 如果没有则生成一条用户记录
        MobileLoginUserDTO mobileLoginUserDTO = userRpcService.getOrCreateUserToken(req.getMobile());

        // 返回登录成功的token
        return ResponseCommon.success(mobileLoginUserDTO);
    }
}
